//
//  XRAFNetworkTool.m
//  框架TEST1
//
//  Created by dllo on 15/12/9.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "XRAFNetworkTool.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager.h"
@implementation XRAFNetworkTool

+ (void)GETUrl:(NSString *)url
          body:(id)body
      headFile:(NSDictionary *)header
      response:(XRResponseStyle)responseStyle
       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
//    // 1. 获取AFN网络请求的Manager
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要监测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    NSString *doucumentPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
    
    // 文件管理器
    NSFileManager *urlCacheManager = [NSFileManager defaultManager];

    // 创建文件夹统一管理
        NSString *urlCache = [doucumentPath stringByAppendingPathComponent:@"urlCache"];
    NSLog(@"%@",urlCache);
    BOOL result1 = [urlCacheManager createDirectoryAtPath:urlCache withIntermediateDirectories:YES attributes:nil error:nil];
    
    if (result1) {
        NSLog(@"创建成功");
    } else {
        
        NSLog(@"创建失败");
    }

    //    NSLog(@"%@",doucumentPath);
    NSString *path = [NSString stringWithFormat:@"%ld",(unsigned long)[url hash]];
    NSString *textFilPath = [urlCache stringByAppendingPathComponent:path];
    
    // 检测网络连接的单例,网络变化时的回调方法
    
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
    }];
    
    NSString *str = [NSString stringWithFormat:@"%@",url];
    
//    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];


    // 2. 请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 3. 数据返回类型的设定 JSON . XML . DATA
    switch (responseStyle) {
        case XRJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case XRXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case XRDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    // 4. 设定响应数据类型。
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    // 5. UTF8
//    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 6. 请求
    [manager GET:str parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        if (responseObject) {
            [netWorkManger stopMonitoring];

            // 写成归档
             [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilPath];
            
            // writeToFile  方法 (基本数据类型)
//            BOOL result = [responseObject writeToFile:textFilPath atomically:YES];
//            
//            if (result) {
//                //            NSLog(@"写入成功");
//            }else{
//                
//                //            NSLog(@"写入失败");
//            }
            success(task, responseObject);
//            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];

        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        if (error) {
            failure(task, error);
            
            
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilPath];
            
            // 按路径取数据 writeToFile
//            id result = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
            
            success(task, result);
                    NSLog(@"失败==== %@", error);

        }
        
    }];
}

+ (void)POSTUrl:(NSString *)url
           body:(id)body
requestBodyStyle:(XRRequestStyle)bodyStyle
       headFile:(NSDictionary *)header
       response:(XRResponseStyle)responseStyle
        success:(void (^)(NSURLSessionDataTask *, id))success
        failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
    // 1. 获取AFN网络请求的Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要监测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    NSString *doucumentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    //    NSLog(@"%@",doucumentPath);
    // 文件管理器
    NSFileManager *urlCacheManagerPost = [NSFileManager defaultManager];
    
    // 创建文件夹统一管理
    NSString *urlCache = [doucumentPath stringByAppendingPathComponent:@"urlCachePost"];
    NSLog(@"%@",urlCache);
    BOOL result1 = [urlCacheManagerPost createDirectoryAtPath:urlCache withIntermediateDirectories:YES attributes:nil error:nil];
    if (result1) {
        NSLog(@"创建成功");
    } else {
        
        NSLog(@"创建失败");
    }
    

    NSString *path = [NSString stringWithFormat:@"%ld",(unsigned long)[url hash]];
    NSString *textFilPath = [urlCache
                             stringByAppendingPathComponent:path];
    
    // 检测网络连接的单例,网络变化时的回调方法
    
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
    }];
    
    NSString *str = [NSString stringWithFormat:@"%@",url];
    
    //    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];


    
    
    // 2. 设置body的类型
    switch (bodyStyle) {
            
        case XRRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case XRRequestString:
            
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
                return parameters;
            }];
             break;
        default:
            break;
    }

    
    
    // 3. 请求头 ---- 通过请求头告诉服务器，客户端的类型
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 4. 数据返回类型的设定 JSON . XML . DATA
    switch (responseStyle) {
        case XRJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case XRXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case XRDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    // 5. 设定响应数据类型。
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/x-javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    // 6. UTF8
     str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 7. 请求
   [manager POST:str parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
       if (responseObject) {
           [netWorkManger stopMonitoring];
           
           success(task, responseObject);
//           BOOL result = [responseObject writeToFile:textFilPath atomically:YES];
           
           // 归档写入
           [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilPath];
           
//           if (result1) {
//               //            NSLog(@"写入成功");
//           }else{
//               
//               //            NSLog(@"写入失败");
//           }
//           NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
           
           
       }
   } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
       if (error) {
           failure(task, error);
//           id result = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
//
           id result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilPath];
           
           success(task, result);
           NSLog(@"失败==== %@", error);

       }
   }];
    
}
@end
